#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>

int main(){
  int epoll_fd = epoll_create(1024);
  if(epoll_fd < 0){
    perror("epoll_create");
    return 0;
  }

  struct epoll_event ev;

  ev.data.fd = 0;
  ev.events = EPOLLIN;
  int ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, 0, &ev);
  if(ret < 0){
    perror("epoll_ctl");
  }

  ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, 1, &ev);
  if(ret < 0){
    perror("epoll_ctl");
  }

  ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, 2, &ev);
  if(ret < 0){
    perror("epoll_ctl");
  }

  ev.events |= EPOLLHUP;
  ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, 1, &ev);
  if(ret < 0){
    perror("epoll_ctl");
  }

  epoll_ctl(epoll_fd, EPOLL_CTL_DEL, 1, nullptr);
  ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, 1, &ev);
  if(ret < 0){
    perror("epoll_ctl");
  }
  else{
    printf("Add success\n");
  }

  //不支持普通文件
  //epoll_ctl: Operation not permitted
  //int fd = open("test.txt", O_RDWR | O_CREAT);
  //ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev);
  //if(ret < 0){
  //  perror("epoll_ctl");
  //}

  //Bad address
  //int ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, 0, nullptr);

  while(1){
    struct epoll_event evs[10];
    //epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
    ret = epoll_wait(epoll_fd, evs, sizeof(evs)/sizeof(evs[0]), 0);
    if(ret < 0){
      perror("epoll_wait");
      continue;
    }
    if(ret == 0){
      printf("epoll_wait timeout\n");
      sleep(1);
      continue;
    }
    for(int i = 0; i < ret; ++i){
      if(evs[i].data.fd == 0){
        char buf[1024] = {0};
        //read(evs[i].data.fd, buf, sizeof(buf) - 1);
        //printf("[%d]:%s\n", evs[i].data.fd, buf);
        read(i, buf, sizeof(buf) - 1);
        printf("[%d]:%s\n", i, buf);
      }
    }
  }

  close(epoll_fd);
  return 0;
}
